import 'package:flutter/material.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/string_util.dart';
import 'package:star_author/widgets/countdown/count_down_view.dart';

///倒计时widget
class CountDownText extends StatefulWidget {
  const CountDownText({
    Key? key,
    required this.endTimeStr,
    required this.builder,
    this.overtimeWidget,
    this.onFinish,
    this.is48Hour = false,
  }) : super(key: key);

  final String endTimeStr;
  final Widget Function(String day, String hour, String minute, String seconds)
      builder;
  final Widget? overtimeWidget;
  final Function? onFinish;
  final bool? is48Hour;

  @override
  State<CountDownText> createState() => _CountDownTextState();
}

class _CountDownTextState extends State<CountDownText> {
  Duration? countdownDuration;

  @override
  void initState() {
    if (widget.endTimeStr.isNotEmpty) {
      DateTime? endAtDateTime = DateUtil.getDateTime(widget.endTimeStr);

      countdownDuration = endAtDateTime?.difference(DateTime.now());
    }
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  @override
  Widget build(BuildContext context) {
    return CountdownView(
      countdownDuration!,
      Duration(seconds: 1),
      (context, remaining) {
        String day = "";
        String hour = "";
        String minute = "";
        String seconds = "";

        day = StringUtil.toTwoDigits(remaining.inDays);

        if (widget.is48Hour!) {
          hour = StringUtil.toTwoDigits(remaining.inHours.remainder(48));
        } else {
          hour = StringUtil.toTwoDigits(remaining.inHours.remainder(24));
        }

        minute = StringUtil.toTwoDigits(remaining.inMinutes.remainder(60));
        seconds = StringUtil.toTwoDigits(remaining.inSeconds.remainder(60));

        return widget.builder(day, hour, minute, seconds);
      },
      widget.overtimeWidget ?? Container(),
      onFinish: () {
        widget.onFinish?.call();
      },
      isStartWhenInit: true,
    );
  }
}
